//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "CTextura.h"

//---------------------------------------------------------------------------

CTextura :: CTextura( ) {
	imagen = NULL;
}

int CTextura :: leerTextura(const char *Textura) {
	bool b = false;


	int namelen = strlen(Textura);
	if ( namelen > 4 )
	{
		char suffix[5];
		strncpy(suffix, Textura + namelen - 4, 4);
		suffix[4] = 0;
		strupr(suffix);

		if ( !strcmp(suffix, ".BMP") )
		{
			FILE* file = fopen(Textura, "rb+");
			if ( file != NULL )
			{
				BITMAPFILEHEADER fileheader;
				BITMAPINFOHEADER infoheader;

				if ( fread(&fileheader, sizeof(BITMAPFILEHEADER), 1, file) == 1
				       && (char)fileheader.bfType == 'B' && *(((char*)&fileheader.bfType) + 1) == 'M'
					&& fread(&infoheader, sizeof(BITMAPINFOHEADER), 1, file) == 1
					&& infoheader.biBitCount == 24 && infoheader.biCompression == BI_RGB )
				{

					rewind( file );
					long offset = fileheader.bfOffBits;
					fseek(file, offset, SEEK_SET);

					int bufsize = infoheader.biWidth * abs(( int ) infoheader.biHeight) * 3;
					unsigned char* imagebuf = new unsigned char[bufsize];

					if ( (int)fread(imagebuf, 1, bufsize, file) == bufsize )
					{
						// Flip the RGB components
						for ( int i = 0; i < bufsize / 3; ++i )
						{
							unsigned char c = imagebuf[ i * 3 ];
							imagebuf[ i * 3 ] = imagebuf[ ( i * 3 ) + 2 ];
							imagebuf[ ( i * 3 ) + 2 ] = c;
						}

						//AbVec2s size((short)infoheader.biWidth, (short)abs((int)infoheader.biHeight));
						tamX = infoheader.biWidth;
						tamY = infoheader.biHeight;
						//image.setValue(size, 3, imagebuf);
						b = TRUE;
					}

					//delete [] imagebuf;
					imagen = imagebuf;
				}

				fclose(file);
			}
		}
	}

	return b;
}

void CTextura :: ponerActiva( ) {
	if( imagen )
		glTexImage2D(GL_TEXTURE_2D,0,3,tamX, tamY,0,GL_RGB,GL_UNSIGNED_BYTE, imagen);
}

void CTextura :: HabilitarTexturas( ) {
	glPixelStorei(GL_UNPACK_ALIGNMENT,1);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glEnable(GL_TEXTURE_2D);
}

CTextura :: ~CTextura( ) {
	if( imagen )
		delete[] imagen;
}

//-------------------------------------------------------------------------
#pragma package(smart_init)